<?php

namespace app\admin\controller\system;


use app\admin\model\SystemAdmin;
use app\admin\model\SystemLog;
use app\common\controller\AdminController;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use think\App;
use think\Exception;
use think\facade\Db;

/**
 * @ControllerAnnotation(title="操作日志管理")
 * Class Auth
 * @package app\admin\controller\system
 */
class Log extends AdminController
{

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new SystemLog();
    }

    /**
     * @NodeAnotation(title="列表")
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            [$page, $limit, $where, $excludeFields] = $this->buildTableParams(['month']);

            $month = (isset($excludeFields['month']) && !empty($excludeFields['month']))
                ? date('Ym', strtotime($excludeFields['month']))
                : date('Ym');
            $permission_ids = session('admin_ids');
            try {
                $count = $this->model->setSuffix('_' . $month)
                    ->withJoin(['admin' => ['id', 'username']], 'LEFT')
                    ->where($where)
                    ->whereIn('admin_id', $permission_ids)//根据所属管理员获取可操作数据
                    ->count();
                $list = $this->model->setSuffix('_' . $month)
                    ->withJoin(['admin' => ['id', 'username']], 'LEFT')
                    ->where($where)
                    ->whereIn('admin_id', $permission_ids)//根据所属管理员获取可操作数据
                    ->page($page, $limit)
                    ->order($this->sort)
                    ->select()->toArray();
            } catch (\Exception $e) {
                $this->error("当前月份没有日志");
                throw new Exception("当前月份没有日志" . $e->getMessage());
            }
            $data = [
                'code' => 0,
//                'msg'   => '',
                'count' => $count,
                'data' => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }


    /**
     * @NodeAnotation(title="清空日志")
     */
    public function delete()
    {
        if ($this->request->isAjax()) {
            $db_name = config('database.connections.mysql.database');
            $del_prefix = config('database.connections.mysql.prefix') . 'system_log_';//需要删除的表前缀
            $sql = "Select CONCAT( 'drop table ', table_name, ';' ) as _sql
                    FROM information_schema.tables 
                    Where table_schema='" . $db_name . "' AND  table_name LIKE '" . $del_prefix . "%';";
            $delete_list = Db::query($sql);//上述sql执行后获取到所有拼接好的，删除表的语句
            foreach ($delete_list as $sql) {
                Db::execute($sql['_sql']);
            }
            $this->success('操作成功');
        }
    }

}